package logutils

import (
	"io"
	"io/ioutil"
	"log"
	"os"
)

var (
	TRACE        *log.Logger
	INFO         *log.Logger
	WARNING      *log.Logger
	ERROR        *log.Logger
	MULTITRACE   *log.Logger
	MULTIINFO    *log.Logger
	MULTIWARNING *log.Logger
	MULTIERROR   *log.Logger
)

func initLog(
	traceHandle io.Writer,
	infoHandle io.Writer,
	warningHandle io.Writer,
	errorHandle io.Writer) {

	TRACE = log.New(traceHandle,
		"TRACE: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	INFO = log.New(infoHandle,
		"INFO: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	WARNING = log.New(warningHandle,
		"WARNING: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	ERROR = log.New(errorHandle,
		"ERROR: ",
		log.Ldate|log.Ltime|log.Lshortfile)

}

func initMultiLog(multiTraceHandler io.Writer) {
	MULTITRACE = log.New(multiTraceHandler,
		"[TRACE]: ",
		log.Ldate|log.Ltime|log.Lshortfile)
	MULTIINFO = log.New(multiTraceHandler,
		"[INFO]: ",
		log.Ldate|log.Ltime|log.Lshortfile)
	MULTIWARNING = log.New(multiTraceHandler,
		"[WARNING]: ",
		log.Ldate|log.Ltime|log.Lshortfile)
	MULTIERROR = log.New(multiTraceHandler,
		"[ERROR]: ",
		log.Ldate|log.Ltime|log.Lshortfile)
}

func Init() {
	logfile, err := os.OpenFile("./httptest.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("Fail to open log file")
	}
	initLog(ioutil.Discard, logfile, logfile, logfile)

	multi := io.MultiWriter(logfile, os.Stdout)

	initMultiLog(multi)

}
